package com.fingard.dsp.bank.directbank.gzrcb01;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.directbank.fngrd01.util.StringHelper;
import com.fingard.dsp.bank.directbank.gzelink01.GZELINK01Base;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2018/5/10.
 */
public class GZRCB01Transaction extends GZRCB01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception{
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo ="";
        retAtsTrans.writeStart();

        int qrySuccessNum = 0;
        try{
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            String opname = "YQ263";
            String plain = bankFront.loginName+"|"+p_req7516.actNum;
            while(tmpIntDateFrom<=tmpIntDateTo && StringHelper.isNullOrEmpty(tmpRespCode)){
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                if(DateHelper.compareMonth(tmpCalendarFrom,tmpCalendarTo)==-1){
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH,tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                }else{
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                int tmpNowReadStart = 1;
                int tmpNowReadNum = 0;
                Map<String,Integer> tmpTotalNum = new HashMap<String, Integer>();
                while (tmpNowReadNum==0 || tmpNowReadNum<tmpTotalNum.get("totalCount")){
                    XmlTextWriter xmlTextWriter = new XmlTextWriter();
                    GZRCB01Header header = new GZRCB01Header();

                    header.chnl_tm  =Format.Date8Format.format(Format.DateTimeFormat.parse(p_req7516.reqHeader.transTime));//前台日期
                    header.chnl_dt =Format.Time6Format.format(Format.DateTimeFormat.parse(p_req7516.reqHeader.transTime));//前台时间
                    header.chnl_seq =p_req7516.reqHeader.transSeqID ;//前台流水号
                    wirteCommenHeader(xmlTextWriter,header);
                    XElement main_data = new XElement("main_data","");
                    main_data.addChild(new XElement("USERID",bankFront.loginName));//用户号
                    main_data.addChild(new XElement("KEHUZH",p_req7516.actNum));//客户号
                    main_data.addChild(new XElement("ZZHHXH",""));//子账户序列号
                    main_data.addChild(new XElement("HUOBDH",convertCurToBank(p_req7516.actCur)));//货币代号
                    main_data.addChild(new XElement("QISHRQ",Format.Date8Format.format(tmpCalendarFrom.getTime())));//起始日期
                    main_data.addChild(new XElement("DAOQRQ",Format.Date8Format.format(tmpClndrStepTo.getTime())));//到期日期
                    main_data.addChild(new XElement("QISHBS",""+tmpNowReadStart));//起始笔数
                    main_data.addChild(new XElement("CXUNBS","10"));//查询笔数
                    main_data.addChild(new XElement("JIEDBZ",""));//借贷标致
                    main_data.addChild(new XElement("SIGDAT",plain));
                    xmlTextWriter.writeXElement(main_data);
                    xmlTextWriter.writeEndDocument();
                    String[] resutlt = sendToBank(xmlTextWriter.toXmlString(),opname);
                    if(resutlt[0].length()==0){
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(resutlt[1].trim(),tmpSbMsg);
                        if(tmpBkReader!=null){
                            String rsp_no = tmpBkReader.getFirstText("/msg/comm_head/rsp_no");
                            String rsp_msg = tmpBkReader.getFirstText("/msg/comm_head/rsp_msg");
                            if("AAAAAAA".equals(rsp_no)||"SUCCESS".equals(rsp_no)){
                                String tmpStartNum =tmpBkReader.getFirstText("/msg/main_data/list_01/QISHBS");
                                String tmpReadNum = tmpBkReader.getFirstText("/msg/main_data/list_01/CXUNBS");
                                String totalCount = tmpBkReader.getFirstText("/msg/main_data/list_01/ZBISHU");
                                if(tmpTotalNum.containsKey("totalCount")){
                                    if(tmpTotalNum.get("totalCount").intValue()!=Integer.valueOf(totalCount).intValue()){
                                        tmpRespCode ="-1";
                                        tmpRespInfo = "相同条件前后查出来的总数不一致";
                                        break;
                                    }
                                }else{
                                    if("0".equals(totalCount)){
                                        break;
                                    }
                                    tmpTotalNum.put("totalCount",Integer.valueOf(totalCount));
                                }
                                int readCount =0;
                                while (tmpBkReader.read("/msg/main_data/list_01/row")){
                                    XElement readXElement = tmpBkReader.readedXElement;
                                    RetAtsTransDetail detail = new RetAtsTransDetail();
                                    detail.tranDate =DateHelper.convertD8toD10(readXElement.getSingleTextNotNull("JIOYRQ").trim());
                                    detail.valueDate = detail.tranDate;
                                    detail.actNum = p_req7516.actNum;
                                    detail.tranTime = detail.valueDate+ " " + DateHelper.getFormat8Time(readXElement.getSingleTextNotNull("JIOYSJ").trim());
                                    detail.comment = readXElement.getSingleTextNotNull("ZHYOMS").trim();
                                    String note = readXElement.getSingleTextNotNull("BEIZXX").trim();
                                    detail.abstr = pickupAbstr(note);
                                    detail.usage = note;
                                    detail.askNumber = readXElement.getSingleTextNotNull("SERNUM").trim();
                                    detail.recAccNum = readXElement.getSingleTextNotNull("DPACNO").trim();
                                    detail.recAccName = readXElement.getSingleTextNotNull("DUIFMC").trim();
                                    detail.recAccBank = readXElement.getSingleTextNotNull("OTHFIN").trim();
                                    detail.cur = convertCurToATS(readXElement.getSingleTextNotNull("HUOBDH").trim());//币种
                                    detail.accBal = readXElement.getSingleTextNotNull("ZHHUYE").trim();//账户余额
                                    detail.tranAmt = readXElement.getSingleTextNotNull("DAYIJE").trim();//交易金额
                                    String cdFlag = readXElement.getSingleTextNotNull("JIEDBZ").trim();//借贷标志 0借1贷
                                    if (cdFlag.equals("1")) {
                                        if(detail.tranAmt.indexOf("-")>=0) {
                                            detail.cdFlag = "1";
                                            detail.tranAmt = detail.tranAmt.substring(1);
                                        }else{
                                            detail.cdFlag = "2";
                                        }
                                    } else if(cdFlag.equals("0")) {
                                        if(detail.tranAmt.indexOf("-")>=0){
                                            detail.cdFlag = "2";
                                            detail.tranAmt = detail.tranAmt.substring(1);
                                        }else{
                                            detail.cdFlag = "1";
                                        }
                                    }else {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = "借贷标志( " + cdFlag + ")无法识别，请与银行核对";
                                        break;
                                    }
                                    retAtsTrans.writeRetDetail(detail);
                                    readCount++;
                                }
                                if("-1".equals(tmpRespCode)){
                                    break;
                                }
                                if(readCount!=Integer.valueOf(tmpReadNum)){
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "统计明细有误";
                                    break;
                                }
                                if(tmpNowReadStart!=Integer.valueOf(tmpStartNum)){
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "查询的起始位置前后不一致";
                                    break;
                                }
                                tmpNowReadStart +=readCount;
                                tmpNowReadNum +=readCount;
                                qrySuccessNum++;
                            }else{
                                if(qrySuccessNum == 0) {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = rsp_msg;
                                }
                                break;
                            }
                        }else{
                            if(qrySuccessNum == 0) {
                                tmpRespCode = "-1";
                                tmpRespInfo = tmpSbMsg.toString();
                            }
                            break;
                        }

                    }else{
                        if(qrySuccessNum == 0) {
                            tmpRespCode = "-1";
                            tmpRespInfo = resutlt[1];
                        }
                        break;
                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        }catch (Exception ex){
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        } else if (retAtsTrans.getWrittenRdCount() == 0) {
            retAtsTrans.writeRespCode("0");
            retAtsTrans.writeRespInfo("交易为空");
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;

    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actArea = p_req7515.actArea;
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        String date = Format.Date8Format.format(new Date());
        p_req7516.dateFrom = date;
        p_req7516.dateTo = date;
        return d_7516_HisTrans(p_req7516);
    }
}
